package com.zhh.srforum.controller;

import com.zhh.srforum.dto.AccessTokenDTO;
import com.zhh.srforum.dto.GiteeUser;
import com.zhh.srforum.mapper.UserMapper;
import com.zhh.srforum.model.User;
import com.zhh.srforum.provider.GiteeProvider;


import com.zhh.srforum.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: Zhao Haihang
 * @Date: 2020/11/03/17:29
 * @Description:
 */
@Controller
@Slf4j
public class AuthorizeController {

    @Autowired
    private GiteeProvider giteeProvider;

    @Value("${gitee.client.id}")
    private String giteeClientId;

    @Value("${getee.client.secret}")
    private String giteeClientSecret;

    @Value("${gitee.redirect_uri}")
    private String giteeRedirectURL;

    @Autowired
    private UserService userService;


    @GetMapping("/callback")
    public String callback(@RequestParam(name="code") String code, HttpServletResponse httpServletResponse){
        //获取token
        AccessTokenDTO accessTokenDTO = new AccessTokenDTO();
        accessTokenDTO.setClient_id(giteeClientId);
        accessTokenDTO.setClient_secret(giteeClientSecret);
        accessTokenDTO.setRedirect_uri(giteeRedirectURL);
        accessTokenDTO.setCode(code);
        accessTokenDTO.setGrant_type("authorization_code");
        String accessToken = giteeProvider.getAccessToken(accessTokenDTO);
        //由token 获取 gitee信息
        GiteeUser giteeUser = giteeProvider.getGithubUser(accessToken);

        if(giteeUser != null && giteeUser.getId() != null){
            //插入数据库
            User user =new User();
            String token = UUID.randomUUID().toString();
            user.setToken(token);
            user.setName(giteeUser.getName());
            user.setAccount(String.valueOf(giteeUser.getId()));
            user.setAvatarUrl(giteeUser.getAvatarUrl());
            userService.createOrUpdate(user);
            httpServletResponse.addCookie(new Cookie("token",token));
            return "redirect:/";
        }else{
            log.error("callback get github error,{}", giteeUser);
            return "redirect:/";
        }
    }

    /**
     * 退出
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/logout")
    public String logout(HttpServletRequest request,HttpServletResponse response){

        request.getSession().removeAttribute("user");

        Cookie cookie  = new Cookie("token", null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);

        return "redirect:";
    }
}
